
import BaseSDK from "./BaseSdk"
import SDKEvent from "./SDKEvent";

const eventTarget = new cc.EventTarget();

export default class KSSDK extends BaseSDK {

    private static _instance: KSSDK = null;
    public static get Instance(): KSSDK {
        this._instance = this._instance || new KSSDK();
        return this._instance;
    }

    private _recorderShareFunc = null;

    private _musicPauseFunc = null;
    private _musicPauseThis = null;
    private _musicResumeFunc = null;
    private _musicResumeThis = null;
    private _clipboardData = "";

    private _playScreenTime = 0;
    private _screenSpaceTime = 0;
    private _interstitiaId = "";
    private _moreGameBtn = null;

    private _recorder = null;//录屏器
    private lastAdTime = 0;//最后一次插屏播放时间
    private _recorderStatus = 0;
    private _recorderEndTime = 0;
    private _recorderTime = 0;

    private _videoId = "";
    private _screenId = "";

    private _shareId = "";
    private _shareUrl = "";
    private _shareTitle = "一起来动脑";
    private _shareDesc = "眼疾手也要快";
    protected _shareOptions = null;

    private _videoLoaded = false;
    private _videoOptions = null;
    private _videoAd = null;
    private lastshockTime = 0;//最后震动时间
    private _shakeState: boolean; //震动的状态

    private _isKSplatform: boolean;

    init() {
        this._isKSplatform = typeof globalThis.KSGameGlobal != 'undefined';
        if (!this._isKSplatform) return;
        this._shakeState = false;
        let that = this;
        this.lastAdTime = new Date().getTime();
        globalThis.ks.onShow((res) => {
            console.log("********游戏回到前台************", res);
        });

        that._preloadVideo();
    }

    public share(options: { success?: Function, fail?: Function }) {
        if (!this._isKSplatform) return;
        this._shareOptions = options;
        globalThis.ks.shareAppMessage({
            templateId: this._shareId || "",
            success: () => {
                options && options.success && options.success();
            },
            fail: () => {
                options && options.fail && options.fail();
            }
        });
    }

    //预载视频广告
    private _preloadVideo() {
        if (!this._isKSplatform) return;
        let that = this;
        //视频广告
        this._videoAd = globalThis.ks.createRewardedVideoAd({ adUnitId: that._videoId });
        this._videoAd.onClose(res => {
            that._videoLoaded = false;
            that.lastAdTime = new Date().getTime();
            if (res && res.isEnded) {
                that._videoOptions && that._videoOptions.success && that._videoOptions.success();
            } else {
                that._videoOptions && that._videoOptions.fail && that._videoOptions.fail();
                // globalThis.wx.showModal({
                //     title: "奖励提醒",
                //     content: "中途关闭视频无法获得奖励，是否继续获得奖励？",
                //     success(res) {
                //         console.log(res);
                //         if (res.confirm) {
                //             that.showRewardVideo(that._videoOptions);
                //         } else if (res.cancel) {

                //         } else {

                //         }
                //     },
                //     fail(res) {
                //         console.log(`showModal调用失败`);
                //     },
                // });
            }
        });
        this._videoAd.onError(res => {
            that._videoLoaded = false;
            console.log("加载失败，尝试重试");
            setTimeout(() => {
                this._videoAd = globalThis.ks.createRewardedVideoAd({ adUnitId: that._videoId });
            }, 10000);
        });
    }

    public login(options) {
        let that = this;
        console.log("快手登录");
        // globalThis.wx.login({
        //     force: options.force,
        //     success(res) {
        //         console.log(`login调用成功`, res);
        //         let userCode: string = res.code;
        //         let visitorCode: string = res.anonymousCode;
        //         let isLogin: boolean = res.isLogin;
        //         if (isLogin) {
        //             globalThis.wx.getUserInfo({
        //                 success(res) {
        //                     let userJson = JSON.stringify(res.userInfo);
        //                     let data = {
        //                         code: userCode,
        //                         json: userJson,
        //                         visitor: false
        //                     };
        //                     that.sendHttpRequest(Common.ttLoginUrl, data, (res) => {
        //                         let result = res.data;
        //                         if (result.user.status == 0) {
        //                             console.log("登录完成，准备回调");
        //                             options.success(result);
        //                         } else {
        //                             console.log("用户状态异常");
        //                             options.fail("你因违规操作,帐号已被系统冻结");
        //                         }
        //                     }, (res) => {
        //                         console.log(`request调用失败`, res);
        //                         options.fail("网络繁忙,请稍后再试");
        //                     })
        //                 },
        //                 fail(res) {
        //                     console.log(`getUserInfo 调用失败`, res);
        //                     //游客登录
        //                     let data = {
        //                         code: visitorCode,
        //                         json: "{}",
        //                         visitor: true
        //                     };
        //                     that.sendHttpRequest(Common.ttLoginUrl, data, (res) => {
        //                         let result = res.data;
        //                         if (result.user.status == 0) {
        //                             console.log("登录完成，准备回调");
        //                             options.success(result);
        //                         } else {
        //                             console.log("用户状态异常");
        //                             options.fail("你因违规操作,帐号已被系统冻结");
        //                         }
        //                     }, (res) => {
        //                         console.log(`request调用失败`, res);
        //                         options.fail("网络繁忙,请稍后再试");
        //                     });
        //                 },
        //             });
        //         } else {
        //             //游客登录
        //             let data = {
        //                 code: visitorCode,
        //                 json: "{}",
        //                 visitor: true
        //             };
        //             that.sendHttpRequest(Common.ttLoginUrl, data, (res) => {
        //                 let result = res.data;
        //                 if (result.user.status == 0) {
        //                     console.log("登录完成，准备回调");
        //                     options.success(result);
        //                 } else {
        //                     console.log("用户状态异常");
        //                     options.fail("你因违规操作,帐号已被系统冻结");
        //                 }
        //             }, (res) => {
        //                 console.log(`request调用失败`, res);
        //                 options.fail("网络繁忙,请稍后再试");
        //             });
        //         }
        //     },
        //     fail(res) {
        //         console.log(`login调用失败`, res);
        //         options.fail("登录失败,请稍后再试");
        //     },
        // });
    }

    public showRewardVideo(options: { success: Function, fail: Function }) {
        let that = this;
        that._videoOptions = options;
        if (!this._isKSplatform) {
            that._videoOptions && that._videoOptions.success && that._videoOptions.success();
            return;
        }
        that._videoAd.show().then((result) => {
            // 激励视频展示成功
            console.log(`show rewarded video ad success, result is ${result}`)
        }).catch((error) => {
            // 激励视频展示失败
            console.log(`show rewarded video ad failed, error is ${error}`)
        })
    }

    //显示插屏广告
    playScreen() {
        if (!this._isKSplatform) return;
        let that = this;
        let now = new Date().getTime();
        if (now - this.lastAdTime > 30000) {
            let interstitialAd = globalThis.ks.createInterstitialAd({
                adUnitId: that._screenId,
            });
            if (interstitialAd) {
                interstitialAd.onClose(res => {
                    // 插屏广告关闭事件
                    that.lastAdTime = new Date().getTime();
                })
                interstitialAd.onError(res => {
                    // 插屏广告Error事件
                })
                let p = interstitialAd.show()
                p.then(function (result) {
                    // 插屏广告展示成功
                    console.log(`show interstitial ad success, result is ${result}`)
                }).catch(function (error) {
                    // 插屏广告展示失败
                    console.log(`show interstitial ad failed, error is ${error}`)
                    if (error.code === -10005) {
                        // 表明当前app版本不支持插屏广告，可以提醒用户升级app版本
                    }
                })
            } else {
                console.log("创建插屏广告组件失败");
            }

        }
    }

    public vibrateShort() {
        if (!this._isKSplatform) return;
        if (this._shakeState) return;
        let now = new Date().getTime();
        if (now - this.lastshockTime > 100) {
            this.lastshockTime = now;
            globalThis.ks.vibrateShort({
                success(res) { },
                fail(res) {
                    console.log(`vibrateShort调用失败`);
                }
            });
        }
    }

    public vibrateLong() {
        if (!this._isKSplatform) return;
        if (this._shakeState) return;
        globalThis.ks.vibrateLong({
            success(res) { },
            fail(res) {
                console.log(`vibrateLong调用失败`);
            }
        });
    }

    public getShakeState(): boolean {
        return this._shakeState;
    }

    public setShakeState(bool: boolean) {
        this._shakeState = bool;
    }


    showToast(content) {
        if (!this._isKSplatform) return;
        globalThis.ks.showToast({
            title: content,
            icon: "success",
            duration: 2000,
            success(res) {
            },
            fail(res) {
            },
        });
    }


    setLocalStorage(key, value) {
        cc.sys.localStorage.setItem(key, value);
    }

    getLocalStorage(key) {
        return cc.sys.localStorage.getItem(key);
    }

    contentSafe(options) {
        let data = { text: options.content };
        // this.sendHttpRequest(Common.contentSafeWX, data, (res) => {
        //     if (res.valid) {
        //         options.callBack(true);
        //     } else {
        //         options.callBack(false);
        //     }
        // }, (res) => {
        //     options.callBack(false);
        // })
    }

    //分包
    public ksSubpackage(name: string, callback?: Function) {
        if (!this._isKSplatform) return;
        globalThis.ks.loadSubpackage({
            name: name, // name 可以填 name 或者 root
            success: (res) => {
                // 分包加载成功后通过 success 回调
                callback && callback(true, res);
            },
            fail: (res) => {
                // 分包加载失败通过 fail 回调
                callback && callback(false, res);
            }
        })
    }
};